<template>
  <div class="app-container">
    <el-row :gutter="20" class="toolbar" type="flex" justify="space-between">
      <!-- 左侧组合 -->
      <el-col :span="16">
        <el-row :gutter="15">
          <el-col :span="10">
            <el-input
                v-model="searchKey"
                placeholder="输入应用名称搜索"
                @keyup.enter.native="handleSearch">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
          </el-col>
        </el-row>
      </el-col>

      <!-- 右侧按钮 -->
      <el-col :span="8" class="text-right">
        <el-button type="primary" @click="handleCreate">创建应用</el-button>
      </el-col>
    </el-row>
    <!-- 数据表格 -->
    <el-table
        :data="appList"
        border
        stripe
        style="width: 100%"
        class="data-table">
      <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center">
      </el-table-column>

      <el-table-column
          prop="appName"
          label="应用名称"
          min-width="150">
      </el-table-column>

      <el-table-column
          prop="creator"
          label="创建人"
          width="120">
      </el-table-column>

      <el-table-column
          prop="createTime"
          label="创建时间"
          width="180">
      </el-table-column>

      <el-table-column
          prop="remark"
          label="应用描述"
          min-width="200">
      </el-table-column>

      <el-table-column
          label="操作"
          width="200"
          align="center">
        <template #default="{row}">
          <el-button
              type="text"
              size="small"
              @click="handleConfig(row)">配置
          </el-button>
          <el-button
              type="text"
              size="small"
              @click="handleView(row)">查看
          </el-button>
          <el-button
              type="text"
              size="small"
              @click="handleToggleStatus(row)">
            {{ row.status === 0 ? '禁用' : '启用' }}
          </el-button>
          <el-button
              type="text"
              size="small"
              style="color: #ff4d4f"
              @click="handleDelete(row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <!-- 新增创建应用对话框 -->
    <el-dialog
        title="创建新应用"
        :visible.sync="createDialogVisible"
        width="600px"
        @close="handleDialogClose">
      <el-form
          :model="createForm"
          :rules="formRules"
          ref="createForm"
          label-position="right"
          label-width="100px">

        <el-form-item label="应用名称" prop="name">
          <el-input
              v-model="createForm.name"
              placeholder="请输入应用名称"
              maxlength="20"
              show-word-limit
              clearable></el-input>
        </el-form-item>

        <el-form-item label="应用介绍" prop="remark">
          <el-input
              type="textarea"
              :rows="4"
              v-model="createForm.remark"
              placeholder="请输入应用描述（可选）"
              maxlength="100"
              show-word-limit
              clearable></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取 消</el-button>
        <el-button
            type="primary"
            :loading="createLoading"
            @click="handleCreateSubmit">确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- 应用详情对话框 -->
    <el-dialog
        title="应用详情"
        :visible.sync="detailDialogVisible"
        width="600px">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="应用ID">
          <span>{{ detailData.appId }}</span>
        </el-form-item>
        <el-form-item label="应用名称">
          <span>{{ detailData.appName }}</span>
        </el-form-item>
        <el-form-item label="创建人">
          <span>{{ detailData.creator }}</span>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ detailData.createTime }}</span>
        </el-form-item>
        <el-form-item label="密钥">
          <span>{{ detailData.appSecret || '无' }}</span>
        </el-form-item>
        <el-form-item label="应用描述">
          <span>{{ detailData.remark || '暂无描述' }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {queryAppPage, createApp, queryAppDetail, updateApp, delApp} from '@/api/gateway-app'

export default {
  data() {
    return {
      selectedApp: '',
      searchKey: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      appList: [],
      // 新增数据项
      createDialogVisible: false,
      createLoading: false,
      createForm: {},
      formRules: {
        name: [
          {required: true, message: '应用名称不能为空', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur'}
        ]
      },
      detailDialogVisible: false,
      detailData: {}
    }
  },
  mounted() {
    this.loadAppData()
  },
  methods: {
    // 加载数据方法
    async loadAppData() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          keywords: this.searchKey,
        }

        const {data} = await queryAppPage(params)
        this.appList = data.records
        this.total = data.total
        // 同步分页信息（根据接口实际情况调整）
        this.currentPage = data.current
        this.pageSize = data.size
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    },

    // 修改后的处理方法
    handleSearch() {
      this.currentPage = 1 // 搜索时重置到第一页
      this.loadAppData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadAppData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadAppData()
    },
    // 修改后的创建方法
    handleCreate() {
      this.createDialogVisible = true
    },
    // 新增方法
    handleDialogClose() {
      this.$refs.createForm.resetFields()
    },

    async handleCreateSubmit() {
      try {
        const valid = await this.$refs.createForm.validate()
        if (!valid) return

        this.createLoading = true
        const response = await createApp({
          name: this.createForm.name,
          remark: this.createForm.remark
        })

        this.$message.success('应用创建成功！')
        // 刷新表格数据
        this.loadAppData()
        // 清空搜索条件（根据业务需求）
        this.searchKey = ''
        // 清空表单
        this.$refs.createForm.resetFields()
        this.createDialogVisible = false
      } catch (error) {
        console.error('创建失败:', error)
      } finally {
        this.createLoading = false
      }
    },
    async handleConfig(row) {
      this.$router.push({ name: 'bind-app-group', query: { id: row.id } })
    },
    async handleView(row) {
      try {
        console.log(row)
        const {data} = await queryAppDetail({id: row.id})
        this.detailData = data
        this.detailDialogVisible = true;
      } catch (error) {
        console.error('获取详情失败:', error);
      }
    },
    handleDelete(row) {
      this.$confirm(`是否删除应用 ${row.appName}？`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await delApp({id: row.id})
          this.$message.success(`删除成功`);
          await this.loadAppData()
        } catch (error) {

        }
      }).catch(() => {
        this.$message.info('操作已取消');
      });
    },
    async handleToggleStatus(row) {
      const status = row.status === 1 ? 0 : 1;
      const action = status === 0 ? '启用' : '禁用';
      this.$confirm(`是否${action}应用 ${row.appName}？`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await updateApp({
            id: row.id,
            status: status,
          });
          row.status = status;
          this.$message.success(`${action}成功`);
        } catch (error) {

        }
      }).catch(() => {
        this.$message.info('操作已取消');
      });
    },
  }
}
</script>

<style scoped>

/* 新增样式 */
.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-textarea {
  resize: vertical;
}

.toolbar {
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.data-table {
  margin-top: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.text-right {
  text-align: right;
}

.detail-dialog .el-form-item {
  margin-bottom: 15px;
}

.detail-dialog .el-form-item span {
  font-weight: bold;
  color: #333;
}

.detail-dialog .dialog-footer {
  text-align: right;
  padding: 10px 0;
}

.detail-dialog .el-dialog__body {
  padding: 20px 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
}
</style>